<?php

class StudentTransfer_MoveoutController extends Zend_Controller_Action
{
    private $_teacherSn; // 教師流水號
    private $_studentParamArr; // 系統變數
    private $_arrayData; // 資料陣列
    public function init()
    {

        $locale = Bootstrap::$config['resources']['locale']['default'];
        $path = APPLICATION_PATH."/modules/student/languages/$locale/data.ini";
        $ini = new Zend_Config_Ini($path);
        $this->_arrayData = $ini->get('array_data')->toArray();
        // 異動類別
        $this->view->transfer_kind_arr = $this->_arrayData['transfer']['kind'];

        // 教師流水號
        $this->_teacherSn = Teacher_Model_Teacher::getSnById($this->view->user->username);

            //取系統預設值
        $param = new Default_Model_ModulesParam();
        $this->_studentParamArr = $param->getParamByResourceId('student');
    }

    public function indexAction()
    {
        $this->_initSemester();
        $form = new StudentTransfer_Form_Moveout();

        $param_arr =  $this->_studentParamArr;

        $form->setDefault('approve_date',date("Y-m-d"));
        $form->setDefault('approve_organ',$param_arr['default_approve_organ']);
        $form->setDefault('approve_word',$param_arr['default_approve_word']);
        $form->setDefault('causation',$param_arr['default_causation_out']);
        $form->setDefault('date',date("Y-m-d"));
        $this->view->form = $form;


    }



    /**
     * 異動資料刪除
     */
    public function deleteDataAction()
    {
        $updateSn = $this->_teacherSn;
        $tempArr = explode("-", $this->view->Semester['yearSeme']) ;
        $sn = (int) $this->getRequest()->getPost('sn');
        $res = Doctrine_Query::create()
        ->from('Student_Model_StudentTransfer')
        ->where('sn=?', $sn)
        ->andWhere('year=?', $tempArr[0])  // 只允許刪除當學期資料
        ->andWhere('semester=?', $tempArr[1])
        ->fetchOne();

        if ($res) {
            $student = new Student_Model_Student();
            $student->assignIdentifier($res->student_sn);
            $student->update_sn = $updateSn;
            $student->study_condition = Student_Model_StudentTransfer::IN_STADY;
            $student->save();
            $res->delete();
            $this->_helper->json($sn);
        }
        else
            $this->_helper->json(0);

    }


    /**
     * 轉出修改
     * @return unknown_type
     */
    public function moveoutEditAction()
    {
        $updateSn = $this->_teacherSn;
        $sdata = $this->getRequest()->getParams();

        $arr = explode("-",$sdata['year_semester']);
        $year = $arr[0];
        $semester = $arr[1];
        $sdata['move_out']['year'] = $year;
        $sdata['move_out']['semester'] = $semester;
        $form = new StudentTransfer_Form_Moveout();
        if($form->isValid($sdata)) {
            $studentTransfer = new Student_Model_StudentTransfer;

            $data = $sdata['move_out'];
            $arr = array();
            $arr['approve_date'] = $data['approve_date'];
            $arr['approve_number'] = $data['approve_number'];
            $arr['approve_organ'] = $data['approve_organ'];
            $arr['approve_word'] = $data['approve_word'];
            $arr['causation'] = $data['causation'];
            $arr['county'] = $data['county'];
            $arr['date'] = $data['date'];
            $arr['school_id'] = $data['school_id'];
            $arr['school_name'] = $data['school_name'];
            $arr['teacher_sn'] = $updateSn;
            $studentTransfer->assignIdentifier($sdata['sn']);
            $studentTransfer->fromArray($arr);
            $studentTransfer->save();
            //$student_transfer->update($arr,array('sn = ?' => $sdata['sn']));
            $this->_helper->json(array('sn'=>$sdata['sn']));
        }
        else
        $this->_helper->json(array('error'=>$form->getMessages()));

    }


    /**
     * 轉出存檔
     * @return unknown_type
     */
    public function moveoutSetAction()
    {
        $updateSn = $this->_teacherSn;
        $data = $this->getRequest()->getParams();
        $arr = explode("-",$data['year_semester']);
        $year = $arr[0];
        $semester = $arr[1];
        $data['move_out']['year'] = $year;
        $data['move_out']['semester'] = $semester;
        $form = new StudentTransfer_Form_Moveout();
        $form->getElement('date')->setValue(date("Y-m-d"));
        //$form->setElementsBelongTo('move_out');
        $message = array();
        if ($form->isValid($data)){
            //找到本學期最後一個異動編號
            $q = Doctrine_Query::create()
            ->select("MAX(school_move_num)  AS mm")
            ->from('Student_Model_StudentTransfer')
            ->where('year=?',$year)
            ->andWhere('semester=?',$semester);
            $res = $q->fetchOne();
            //  echo $res->mm; exit;
            $data['move_out']['school_move_num'] = $res->mm + 1;
            //$data['move_out']['sn'] = null;
            $data['move_out']['teacher_sn'] = $updateSn;
            $data['move_out']['student_sn'] = $data['student_sn'];
            $studentTransfer = new Student_Model_StudentTransfer();
            $studentTransfer->fromArray($data['move_out']);
            $studentTransfer->save();

            $student = new Student_Model_Student();
            $student->assignIdentifier($data['student_sn']);
            $student->update_sn = $updateSn;
            $student->study_condition = $data['move_out']['causation_kind'];
            $student->save();

            $this->_helper->json(array('sn'=>$data['sn']));
        }
        else
        $this->_helper->json(array('error'=>$form->getMessages()));

    }

    /**
     * 初始化學期
     * @return unknown_type
     */
    private function _initSemester()
    {
        if ($this->getRequest()->getParam('year_semester')){
            $this->view->year_semester = $this->getRequest()->getParam('year_semester');
            echo $this->getRequest()->getParam('year_semester').'--';
            $this->view->class_id = $this->getRequest()->getParam('class_id');
        }
        else{
            $this->view->year_semester = $this->view->Semester['year'].'-'.$this->view->Semester['semester'];
        }


    }

    /**
     *  取出班級
     */
    public function getclassAction()
    {
        $this->getHelper('layout')->disableLayout();
        $this->getHelper('ViewRenderer')->setNorender();
        $year_semester = $this->getRequest()->getParam('year_semester');

        echo $this->view->ClassNameOptions($year_semester);
        //exit;
    }

    /**
     *  該學期所有學生
     */
    public function getStudentAction()
    {
        $this->getHelper('layout')->disableLayout();
        $request = $this->getRequest();
        if ($request->getParam('year_semester')) {
            $arr = explode("-",$request->getParam('year_semester'));
            $year = (int)$arr[0];
            $semester =(int) $arr[1];
        }
        else {
            $year = $this->view->Semester['year'];
            $semester = $this->view->Semester['semester'];
        }
        $kind = $request->getParam('kind');
        $q = Doctrine_Query::create()
        ->select('a.*, b.name AS name, b.identification_number AS identification_number, b.sex AS sex,
          c.student_id AS student_id, c.grade AS grade, c.class_sn AS class_sn, c.number AS number')
        ->from('Student_Model_StudentTransfer a ')
        ->leftJoin('a.Student_Model_Student  b')
        ->leftJoin('b.Student_Model_StudentSemester c')
        ->where('a.year=c.year AND a.semester=c.semester')
        ->andWhere('c.year=?', $year)
        ->andWhere('c.semester=?',$semester)
        ->andWhereIn('a.causation_kind',array(
        Student_Model_StudentTransfer::ABROAD,
        Student_Model_StudentTransfer::REDEPLOYMENT,
        Student_Model_StudentTransfer::REDEPLOYMENT,
        ))
        ->orderBy('a.date DESC');
        $res = $q->fetchArray();
        $this->view->data = $res;
    }


    /**
     * 班級學生名單
     * @return unknown_type
     */
    public function getstudentsAction()
    {
        $this->getHelper('layout')->disableLayout();
        $this->getHelper('ViewRenderer')->setNorender();
        $yearSemester = $this->getRequest()->getParam('year_semester');
        if (!$yearSemester)
        $yearSemester = $this->view->Semester['year'].'-'.$this->view->Semester['semester'];
        $class_id = $this->getRequest()->getParam('class_id');
        echo $this->view->StudentNameOptions($yearSemester,$class_id,'',Student_Model_StudentTransfer::IN_STADY);
        //   exit;
    }

    /**
     *  取出異動資料
     */
    public function getTransferDataByidAction()
    {
        $sn = (int)$this->getRequest()->getParam('sn');
        $core = new StudentTransfer_Model_Core();
        $res = $core->getTransferDataByid($sn);
        $this->_helper->json($res);
    }

    /**
     *  列印期中轉學證明書
     */
    public function printCertiAction()
    {
        $this->getHelper('layout')->setLayout('print-style');
        // 學籍參數
        $this->view->studentParam = $this->_studentParamArr;
        // 資料陣列
        $this->view->arrayData = $this->_arrayData ;


        $sn = (int) $this->_getParam('sn');
        $res =  Doctrine_Query::create()
        //->select('a.*, b.name AS name, ')
        ->from('Student_Model_StudentTransfer a')
        ->leftJoin('a.Student_Model_Student b')
        ->leftJoin('b.Student_Model_StudentSemester c')
        ->where('a.sn=?', $sn)
        ->orderBy('c.year DESC, c.semester DESC')
        ->fetchOne();
        $this->view->studentData = $res;
        // 期中成績資料
        $year = $res->Student_Model_Student->Student_Model_StudentSemester[0]->year;
        $semester = $res->Student_Model_Student->Student_Model_StudentSemester[0]->semester;
        $grade = $res->Student_Model_Student->Student_Model_StudentSemester[0]->grade;
        $studentSn = $res->Student_Model_Student->sn;
        $res = Doctrine_Query::create()
        ->select('a.*, b.subject_sn AS subject_sn, b.test_kind as test_kind, b.test_sort as test_sort')
        ->from('Student_Model_StudentScoreStageDetail a')
        ->leftJoin('a.Student_Model_StudentScoreStage b')
        ->leftJoin('b.Semester_Model_SemesterSubject c')
        ->where('a.student_sn=?', $studentSn)
        ->andWHere('b.subject_sn=c.subject_sn')
        ->andWhere('c.year=?', $year)
        ->andWhere('c.semester=?', $semester)
        ->fetchArray();
        $arr = array();
        foreach ($res as $row) {
            $arr[$row['test_sort']][$row['test_kind']][$row['subject_sn']] = $row['score'];
        }
        $this->view->scores = $arr;

        // 班級陣列
        $semesterClass = new Semester_Model_SemesterClass();
        $this->view->semesterClass = $semesterClass->getClassNames($year,$semester);


        // 日常生活表現
        $res = Doctrine_Query::create()
        ->from('Student_Model_StudentScoreComment')
        ->where('year=?', $year)
        ->andWhere('semester=?', $semester)
        ->andWhere('student_sn=?', $studentSn)
        ->fetchArray();

        $commentArr = array();
        foreach($res as $row)
        $commentArr[$row['score_type']] = $row['comment'] ;

        $this->view->comment = $commentArr;

         // 目前學期
        $semesterDuration = new Semester_Model_SemesterDuration();
        $semesterDurationAll = $semesterDuration->getAllYearSemester();
        $this->view->currSemester = $semesterDurationAll[$year.'-'.$semester];

        $semesterSubjet = new Semester_Model_SemesterSubject();
        $this->view->semesterSubjetArr = $semesterSubjet->getSubject($year, $semester,$grade);
//print_r($this->view->semesterSubjetArr);
    }

}
